/*
 * BGSubstraction.cpp
 *
 *  Created on: Mar 31, 2010
 *      Author: Víctor Gaspar
 *
 *  NOTES: Todos los comentarios los dejo para que
 *  se pueda probar a posteriori paso a paso
 */

#include <cv.h>
#include <cvaux.h>
#include <highgui.h>
#include <stdio.h>
#include <sstream>
#include <sys/stat.h>

std::string PATH;
std::string OUTPATH;

bool FileExists(std::string strFilename) {
  struct stat stFileInfo;
  bool blnReturn;
  int intStat;

  // Attempt to get the file attributes
  intStat = stat(strFilename.c_str(),&stFileInfo);
  if(intStat == 0)
    blnReturn = true;
  else
    blnReturn = false;

  return(blnReturn);
}

// Foreground and Background extraction
int main(int argc, char* argv[]) {

	if(argc > 3)
	{
		printf("Too many arguments supplied.\n");
		exit(0);
	} else if (argc < 3){
		printf("Too few arguments supplied.\n");
		exit(0);
	}

	PATH = argv[1];
	OUTPATH = argv[2];

	std::stringstream out;
	std::string file_name = PATH;

	int fr = 1;
	out << fr;

	file_name += out.str();
	file_name += ".jpg";

	IplImage* tmp_image = cvLoadImage(file_name.c_str());

	if (!tmp_image) {
		printf("bad image \n");
		exit(0);
	}

	//cvNamedWindow("BG", 1);
	//cvNamedWindow("FG", 1);
	//cvNamedWindow("IMG", 1);

	//create BG model
	CvBGStatModel* bg_model = cvCreateGaussianBGModel(tmp_image);

	// Obtener el background a partir de un max de 30 imagenes
	for (fr = 2; fr<=30; fr++) {
		//double t = (double) cvGetTickCount();

		// Get new image
		std::stringstream out;
		std::string file_name = PATH;
		out << fr;
		file_name += out.str();
		file_name += ".jpg";

		if(FileExists(file_name))
		{
			tmp_image = cvLoadImage(file_name.c_str());

			// Update model
			cvUpdateBGStatModel(tmp_image, bg_model);
			//t = (double) cvGetTickCount() - t;

			// show time
			//printf("ms: %.1f\n", t / (cvGetTickFrequency() * 1000.));
			//printf("%s\n", file_name.c_str());

			// show images
			//cvShowImage("BG", bg_model->background);
			//cvShowImage("FG", bg_model->foreground);
			//cvShowImage("IMG", tmp_image);

			//int k = cvWaitKey();
			//if (k == 27)
			//	break;
		}
	}

	cvSaveImage(OUTPATH.c_str(), bg_model->background);

	cvReleaseBGStatModel(&bg_model);
	cvReleaseImage(&tmp_image);

	return 0;
}

